import 'package:flutter/material.dart';
import 'package:flutter_cwhisky/component/text_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../common/style/colors.dart';
import '../common/style/images.dart';
import 'shape/half_painter.dart';
import 'tab_icons.dart';

class AppBottomBar extends StatefulWidget {
  const AppBottomBar({
    Key? key,
    this.selectedPosition = 0,
    required this.selectedCallback,
    required this.iconList,
  }) : super(key: key);

  /// 选中下标
  final int selectedPosition;
  final Function(int selectedPosition) selectedCallback;
  final int towerPosition = 2;
  final List<TabIconData> iconList;
  final Color? backgroundColor = Colors.white;

  @override
  _AppBottomBarState createState() => _AppBottomBarState();
}

class _AppBottomBarState extends State<AppBottomBar> with TickerProviderStateMixin {
  /// BottomNavigationBar高度
  double barHeight = 48.0.h;

  /// 指示器高度
  // double indicatorHeight = 44.0;
  double indicatorSize = 32.r;

  /// 指示器 距离顶部高度
  double indicatorMarginTop = 2.0;

  /// 选中下标
  int selectedPosition = 0;

  /// 记录上一次的选中下标
  int previousSelectedPosition = 0;

//  / 选中图标高度
  // double selectedIconHeight = 28.0;

  /// 默认图标高度
  double normalIconSize = 22.r;

  double itemWidth = 0;

  late AnimationController controller;
  late Animation<double> animation;

  final myCurve = const Cubic(0.68, 0, 0, 1.6);

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        itemWidth = context.size!.width / widget.iconList.length;
      });
    });

    /// 设置动画时长
    controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 400),
    );

    selectedPosition = widget.selectedPosition;
    previousSelectedPosition = widget.selectedPosition;
    animation = Tween(begin: selectedPosition.toDouble(), end: selectedPosition.toDouble())
        .animate(CurvedAnimation(parent: controller, curve: myCurve));
  }

  @override
  Widget build(BuildContext context) {
    final children = <Widget>[];
    if (itemWidth == 0) {
      return Stack(clipBehavior: Clip.none, children: children);
    }

    for (var i = 0; i < widget.iconList.length; i++) {
      /// 每个Icon 格子  && title
      children.add(Flexible(
        flex: 1,
        child: TabIcons(
          tabIconData: widget.iconList[i],
          isChecked: selectedPosition == i,
          normalIconSize: normalIconSize,
          removeAllSelect: () => _selectedPosition(i),
        ),
      ));
    }

    return Stack(
      clipBehavior: Clip.none,
      alignment: Alignment.topCenter,
      children: [
        Container(
          height: barHeight + MediaQuery.of(context).padding.bottom,
          clipBehavior: Clip.none,
          child: Row(
            children: children,
          ),
        ),
        // Positioned(
        //   top: -15.h,
        //   left: 0,
        //   right: 0,
        //   child: IgnorePointer(
        //     child: Container(
        //       decoration: const BoxDecoration(color: Colors.transparent),
        //       child: Align(
        //         heightFactor: 0.5,
        //         alignment: const Alignment(0, -1),
        //         //_positionAnimation.value控制这个叠叠的圆的位置，根据点的导航修改圆的x轴的位置
        //         child: FractionallySizedBox(
        //           widthFactor: 1 / 3, //控制占的宽度
        //           child: Stack(
        //             alignment: Alignment.center,
        //             children: <Widget>[
        //               Container(
        //                 height: 64.h,
        //                 width: 47.w,
        //                 decoration: BoxDecoration(
        //                     color: widget.backgroundColor,
        //                     border: Border(top: BorderSide(color: AppColors.colorE6, width: 1)),
        //                     borderRadius: BorderRadius.only(
        //                       topLeft: Radius.circular(100),
        //                       topRight: Radius.circular(100),
        //                     )),
        //                 child: Column(
        //                   mainAxisSize: MainAxisSize.min,
        //                   children: [
        //                     Image(
        //                       image: const AssetImage(AppImages.tabAddSelected),
        //                       height: 39.r,
        //                       width: 39.r,
        //                       fit: BoxFit.cover,
        //                     ),
        //                     Container(
        //                       margin: EdgeInsets.only(top: 4.h),
        //                       child: TextView(
        //                         text: '送拍',
        //                         fontColor: AppColors.color33,
        //                         fontSize: 10.sp,
        //                       ),
        //                     )
        //                   ],
        //                 ),
        //
        //                 // child: ClipRect(
        //                 //     clipper: HalfClipper(), //裁剪
        //                 //     child: Center(
        //                 //       child: Container(
        //                 //           height: 64.h,
        //                 //           width: 47.w,
        //                 //           decoration: BoxDecoration(
        //                 //               color: widget.backgroundColor,
        //                 //               shape: BoxShape.circle,
        //                 //               boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 2)])),
        //                 //     )),
        //               ),
        //               // SizedBox(
        //               //     height: 44.h,
        //               //     width: 64.w,
        //               //     child: CustomPaint(
        //               //       painter: HalfPainter(),
        //               //     )),
        //               // Container(
        //               //   height: 64.h,
        //               //   width: 47.w,
        //               //   padding: EdgeInsets.only(top: 14),
        //               //   child: Column(
        //               //     children: [
        //               //       Image.asset(
        //               //         widget.iconList[widget.towerPosition].icon,
        //               //         width: 39.r,
        //               //         height: 39.r,
        //               //       ),
        //               //       TextView(text: '送牌')
        //               //     ],
        //               //   ),
        //               // )
        //             ],
        //           ),
        //         ),
        //       ),
        //     ),
        //   ),
        // ),
      ],
    );
  }

  void _selectedPosition(int position) {
    /// 去除重复点击
    // if (position == selectedPosition) return;

    previousSelectedPosition = selectedPosition;
    selectedPosition = position;

    /// 执行动画
    animation = Tween(begin: previousSelectedPosition.toDouble(), end: selectedPosition.toDouble())
        .animate(CurvedAnimation(parent: controller, curve: myCurve));

    controller.forward(from: 0.0);

    widget.selectedCallback(selectedPosition);
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

class TabIconData {
  String? title;
  String icon;
  String? selectIcon;
  int dot;
  bool animate;

  /// icon 动画
  AnimationController? animationController;

  TabIconData({this.title, required this.icon, this.selectIcon, this.dot = 0, this.animate = true});
}

//裁剪成三分之一
class HalfClipper extends CustomClipper<Rect> {
  @override
  Rect getClip(Size size) {
    final rect = Rect.fromLTWH(0, 20, size.width, 20.h);
    return rect;
  }

  @override
  bool shouldReclip(CustomClipper<Rect> oldClipper) {
    return true;
  }
}

class MyClipper extends CustomClipper<Path> {
  /// 顶部向下填充，用于给普通item布局使用。
  final double inset;

  /// 中心圆 半径
  final double circleRadius;

  /// 中心圆旁边的 影响radius
  final double effectRadius;

  MyClipper({
    required this.inset,
    required this.circleRadius,
    required this.effectRadius,
  }) : assert(inset > effectRadius);

  @override
  Path getClip(Size size) {
    var path = Path();
    double centerX = size.width / 2.0;

    path.moveTo(0, inset);
    path.lineTo(centerX - circleRadius - effectRadius, inset);

    // 左侧半圆
    {
      var c1 = Offset(centerX - circleRadius + effectRadius, inset);
      var c2 = Offset(centerX - (circleRadius + effectRadius) / 2.0, 0);
      var c3 = Offset(centerX, 0);

      path.cubicTo(c1.dx, c1.dy, c2.dx, c2.dy, c3.dx, c3.dy);
    }
    // 右侧半圆。
    {
      var c1 = Offset(centerX + (circleRadius + effectRadius) / 2.0, 0);
      var c2 = Offset(centerX + circleRadius - effectRadius, inset);
      var c3 = Offset(centerX + circleRadius + effectRadius, inset);

      path.cubicTo(c1.dx, c1.dy, c2.dx, c2.dy, c3.dx, c3.dy);
    }

    path.lineTo(size.width, inset);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);
    path.lineTo(0, inset);

    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
    return true;
  }
}
